package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.aspect.annotation.OperLog;
import com.itheima.common.R;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;



import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    /**
     * 用户登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.根据用户名判断
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(lqw);
        if (emp == null) {
            return R.error("用户名不存在");
        }

        //2.根据密码判断
        String password = employee.getPassword();
        //MD5加密方法
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info(pwd);
        if (!emp.getPassword().equals(pwd)) {
            return R.error("密码错误");
        }
//  根据bcrypt加盐加密方法进行加密,更加安全高效
//    String gensalt = BCrypt.gensalt();
//    String hashpw = BCrypt.hashpw(password, gensalt);
//        log.info(hashpw);
//        boolean checkpw = BCrypt.checkpw(password, emp.getPassword());
//        if (!checkpw) {
//            return R.error("密码错误");
//        }

        //3.根据账号状态判断
        if (emp.getStatus() == 0) {
            return R.error("账号禁用");
        }

        //4.登陆成功
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 用户退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清理session中保存的当前员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 分页查询所有
     *
     * @param page     当前页
     * @param pageSize 每页条数
     * @param name     可选条件参数
     * @return
     */
    @OperLog(value = "分页查询页面信息",username = "admin")
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page={},pageSize={},name={}", page, pageSize, name);
        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);

    }

    /**
     * 添加用户
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("新增员工信息:{}", employee.toString());
        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置元数据对象处理器后 可以不用手动更新数据 可以注释
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //获得当前登录用户的id
//        long empId = (long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);
        employeeService.save(employee);
        return R.success("添加成功");

    }

    /**
     * 根据id查询用户信息进行修改前的数据回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable long id) {
        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);

        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到对应的;员工信息");
    }

    /**
     * 根据id修改信息(个人信息and状态码:禁用/启用)
     *
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        //打印用户信息
        log.info(employee.toString());
        //获取用户id
        long empId = (long) request.getSession().getAttribute("employee");
        //封装修改时间
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);
        //调用修改方法
        employeeService.updateById(employee);
        //返回结果
        return R.success("员工信息修改成功");
    }

}
